package com.micro.turtle.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.micro.turtle.constant.Token;
import com.micro.turtle.constant.Url;
import java.util.Arrays;
import java.util.List;

/**
 * Api工具
 *
 * @author jason.lv
 * @since 2022/1/21 14:03
 */
public class Api {


    private static HttpRequest createGet(Url url) {
        HttpRequest request = HttpUtil.createGet(url.getUri());
        request.header("PRIVATE-TOKEN", Token.ACCESS_TOKEN);
        return request;
    }

    private static HttpRequest createPost(Url url) {
        HttpRequest request = HttpUtil.createPost(url.getUri());
        request.header("PRIVATE-TOKEN", Token.ACCESS_TOKEN);
        request.method(Method.POST);
        return request;
    }

    public static <R> List<R> getList(Url url, Class<R> clazz) {
        HttpRequest request = createGet(url);
        HttpResponse response = request.execute();
        if (isFail(response)) {
            return null;
        }
        return JSONUtil.toList(response.body(), clazz);
    }

    public static <R> R get(Url url, Class<R> clazz) {
        HttpRequest request = createGet(url);
        HttpResponse response = request.execute();
        if (isFail(response)) {
            return null;
        }
        return JSONUtil.toBean(response.body(), clazz);
    }

    public static <R> R post(Url url, Class<R> clazz) {
        return post(url, null, clazz);
    }

    public static <R> R post(Url url, Object req, Class<R> clazz) {
        HttpRequest request = createPost(url);
        if (ObjectUtil.isNotNull(req)) {
            request.body(JSONUtil.toJsonStr(req));
        }
        HttpResponse response = request.execute();
        if (isFail(response)) {
            return null;
        }
        return JSONUtil.toBean(response.body(), clazz);
    }

    public static <R> R delete(Url url, Class<R> clazz) {
        return delete(url, null, clazz);
    }

    public static <R> R delete(Url url, Object req, Class<R> clazz) {
        HttpRequest request = createPost(url);
        request.method(Method.DELETE);
        request.body(JSONUtil.toJsonStr(req));
        HttpResponse response = request.execute();
        if (isFail(response)) {
            return null;
        }
        return JSONUtil.toBean(response.body(), clazz);
    }

    final static List<Integer> FAIL_CODE = Arrays.asList(401, 400);

    private static boolean isFail(HttpResponse response) {
        if (FAIL_CODE.contains(response.getStatus())) {
            Log.info(response.getStatus() + " " + response.body());
            return true;
        }
        return false;
    }

}
